package global

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"time"
)

func InitLogger() {
	now := time.Now()
	filename := fmt.Sprintf("logs/%04d-%02d-%02d.log", now.Year(), now.Month(), now.Day())
	// 由于zap不具备日志切割功能, 这里使用lumberjack配合
	hook := &lumberjack.Logger{
		Filename:   filename,             // 日志文件路径
		MaxSize:    Conf.Logs.MaxSize,    // 文件最大大小，MB
		MaxAge:     Conf.Logs.MaxAge,     // 最大存放天数
		MaxBackups: Conf.Logs.MaxBackups, // 备份数
		Compress:   Conf.Logs.Compress,
	}
	defer hook.Close()

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder

	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig), // 编码器配置
		zapcore.NewMultiWriteSyncer(
			zapcore.AddSync(os.Stdout), // 输出到控制台和文件
			zapcore.AddSync(hook),
		),
		Conf.Logs.Level, // 日志等级
	)

	logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	Logger = logger.Sugar()
	Logger.Debug("初始化日志完成...")
}
